package com.tianlang.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.util.RedirectUrlBuilder;

/**
 * 
 * @author mchp 
 * 在拦截后,进入登录页面前,把被拦截地址放入session中。登录成功返回被拦截界面
 * 结合MyAuthenticationSuccessHandler
 */
public class LoginUrlEntryPoint implements AuthenticationEntryPoint {
	
	@SuppressWarnings("unused")
	private static Logger LOG = Logger.getLogger(LoginUrlEntryPoint.class);
	
	@Override
	public void commence(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException authException) throws IOException, ServletException {

		String returnUrl = buildHttpReturnUrlForRequest(request);
		request.getSession().setAttribute("ru", returnUrl);

		String targetUrl = null;
		String url = request.getRequestURI();
		if (url.indexOf("admin") != -1) {
			targetUrl = "/admin/login";
		} else {
			targetUrl = "/member/login";
		}
		targetUrl = request.getContextPath() + targetUrl;
		response.sendRedirect(targetUrl);
	}

	protected String buildHttpReturnUrlForRequest(HttpServletRequest request) throws IOException, ServletException {
		RedirectUrlBuilder urlBuilder = new RedirectUrlBuilder();
		urlBuilder.setScheme("http");
		urlBuilder.setServerName(request.getServerName());
		urlBuilder.setPort(request.getServerPort());
		urlBuilder.setContextPath(request.getContextPath());
		urlBuilder.setServletPath(request.getServletPath());
		urlBuilder.setPathInfo(request.getPathInfo());
		urlBuilder.setQuery(request.getQueryString());
		return urlBuilder.getUrl();
	}
}
